package cn.itsource.user.service.impl;

import cn.itsource.basic.util.SMSUtil;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.ICodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CodeServiceImpl implements ICodeService {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate template;


    //{"phone":"11","type":"register"}
    @Override
    public void sendCode(Map<String, String> map) {
        //手机号
        String phone = map.get("phone");
        //验证码类型
        String type = map.get("type");
        // 1.后台验证手机号（空验证）
        if (phone == null || phone.length() == 0) {
            throw new RuntimeException("手机号不能为空！");
        }

        // 3.生成验证码
        String code = StrUtils.getRandomString(6);
        Object o = template.opsForValue().get(phone + ":" + type);
        if (o!=null){//已近在redis里面有存放的验证码
            //判断两次请求的间隔是否大于一分钟
            String strCode = (String) o;
            //k  15008495702:register  v 782168:163948646846
            //获得上一次存储验证码的时间
            Long startTime = Long.valueOf(strCode.split(":")[1]);
            if(System.currentTimeMillis()-startTime<60*1000){//两次请求间隔小于60秒
                throw  new RuntimeException("验证码已发送，请不要重复发送");
            }
            //大于60 需要重复发送验证码【和上一次相同验证码】 782168:163948646846
            code=strCode.split(":")[0];
        }
        //4.保存到redis
        //k  15008495702:register  v 782168:163948646846当前系统的毫秒数
        template.opsForValue().set(phone+":"+type,code+":"+System.currentTimeMillis(),5, TimeUnit.MINUTES);
        System.out.println("本次的验证码为："+code);
        // 5.发送验证码【第三方接口】
        //SMSUtil.send(phone, code);


    }
}
